﻿var refreshlistticket;
$(document).ready(function () {
    var height = $(window).height() - $(".ticket-filter").offset().top;
    $(".ticket-filter").css("height", height - 150);
    //$(".ticket-result").css("height", height - 200);
    $("#divListCurrentTicket").css("height", height - 200);
    $(".group-filter-tree-bg").css("height", height - 170);
    $(".ticket-activities-scroll").css("height", height - 150);
    $(".ticket-filter li").click(function () {
        $(".ticket-filter li").removeClass("ticket-filter-active");
        $(this).addClass("ticket-filter-active");
    });
    $(".ticket-filter-curent li").click(function () {
        $(".ticket-filter-curent li").removeClass("active");
        $(this).addClass("active");

    });
    $("#dashboard li a[href='#currentticket']").click(function () {
        $(".search-tab").hide();
        $(".btn-refresh-board").show();
    });
    $("#dashboard li a[href='#allticket']").click(function () {
        if (!$(this).hasClass("isLoaded")) {
            $(this).addClass("isLoaded");
            FilterTicket(null, 15, $('#divListTicket'));
            autorefreshdepartment();
        }
        $(".search-tab").show();
        $(".btn-refresh-board").hide();
    });
    setInterval(function () {
        $(".btn-refresh-activities").html("<i class='icon-refresh icon-spin'></i>");
        setTimeout(function () {
            $(".btn-refresh-activities").html("");
        }, 2e3);
        $.ajax({
            url: '/Ticket/ListActivities',
            success: function (data) {
                $(".ticket-activities").html(data);
            }
        });
    }, 10000);
    $(".btn-refresh-board").click(function () {
        $(".btn-refresh-board i").addClass("icon-spin");
        refreshlistcurrent();
        FilterTicket(null, 7, $('#divListTicket'));

    });


    initJQueryViewTicket(0);
    $(".ticketfilter li p").click(function () {
        $(this).find("a").addClass("ticket-status-selected");
        $(".ticketfilter li ul li p").not(this).find("a").removeClass('ticket-status-selected');
    });

    $("#fr-searchticketid").submit(function () {
        App.blockUI($('#dashboard'));
        $.ajax({
            url: "/ticket/searchticket",
            data: $(this).serialize(),
            success: function (data) {
                if (data == "") {
                    alert("Ticket not found");
                } else {
                    $('#divListTicket').html(data);
                    $('.showSummary').tooltip111();
                    var height = $(".ticket-filter").height();
                    $(".listticketresult").slimScroll({
                        height: height - 60,
                        alwaysVisible: false
                    });
                }
                App.unblockUI($('#dashboard'));
            }, error: function () {
                //alert("OrderRef or TicketID invalid");
                App.unblockUI($('#dashboard'));
            }
        });
        return false;
    });
    //initformlistticket();
    $(".btn-deletetickets").click(function () {
        if (confirm("Are you sure?")) {
            checkD = 0;
            $('#divListTicket #fr-listticket').submit();
        }
    });
    $('#btn-assignto').click(function () {
        checkD = 1;
        $('#divListTicket #fr-listticket').submit();
    });

    $("#listcurrentticket table input[type='checkbox']").hide();

    autorefreshcurrentticket();

});

var checkD = 0;

function autorefreshcurrentticket() {
    $(".btn-refresh-board i").addClass("icon-spin");
    setTimeout(function () {
        $(".btn-refresh-board i").removeClass("icon-spin");
    }, 2e3);
    setInterval(function () {
        $.ajax({
            url: "/ticket/countticketcurrent",
            success: function (data) {
                $(".newtickets").html(data.new);
                $(".opentickets").html(data.open);
                $(".startedtickets").html(data.started);
                $(".pendingtickets").html(data.pending);
                $(".unsolvedtickets").html(data.unsolved);
            }
        });
        $(".ticket-filter-curent li.active").trigger("click");
    }, 30000);
}

function refreshTree() {
    //App.blockUI($('.tickettree'));
    $(".btn-refresh-tickettree i").addClass("icon-spin");
    $.ajax({
        url: '/Ticket/TicketTree',
        success: function (data) {
            var arr = $.parseJSON(data);
            $('.num-tick').each(function (index, option) {
                option.innerHTML = " (" + arr[index] + ")";
            });
            $(".btn-refresh-tickettree i").removeClass("icon-spin");
            //App.unblockUI($('.tickettree'));
        },
        error: function (ex) {
            alert("Refresh Error");
            $(".btn-refresh-tickettree i").removeClass("icon-spin");
            //App.unblockUI($('.tickettree'));
        }
    });
}

function autorefreshdepartment() {
    setInterval(function () {
        $(".btn-refresh-tickettree").html("<i class='icon-refresh icon-spin'></i>");
        setTimeout(function () {
            $(".btn-refresh-tickettree").html("");
        }, 2e3);
        $.ajax({
            url: '/Ticket/TicketTree',
            success: function (data) {
                var arr = $.parseJSON(data);
                $('.num-tick').each(function (index, option) {
                    option.innerHTML = " (" + arr[index] + ")";
                });
            }
        });
    }, 30000);
}

function tabticketclose(ticketId) {
    var isActive = $("#close" + ticketId).parent().hasClass("active");
    $("#viewticket_" + ticketId).remove();
    $("#close" + ticketId).parent().remove();
    if (isActive) {
        $(".ticket-tabs li:last-child").addClass("active");
        $($(".ticket-tabs li:last-child a").attr("href")).addClass("active");
    }
}

function viewticket(ticketId, subject) {
    App.blockUI($('#dashboard'));
    $.ajax({
        url: '/Ticket/TicketDetails',
        data: { ticketId: ticketId },
        success: function (data) {
            $("#tabViewTicket li").removeClass("active");
            $("#tabpanel-viewticket .tab-pane").each(function () {
                if (!$(this).hasClass("tab-pane-dashboard"))
                    $(this).removeClass("active");
            });
            if ($('#viewticket_' + ticketId).length > 0) {
                $('#a_viewticket_' + ticketId).parent().addClass("active");
                $('#viewticket_' + ticketId).addClass("active");
            } else {
                $("#tabViewTicket").append("<li class='active'>" +
                    "<a href='#viewticket_" + ticketId + "' data-toggle='tab' id='a_viewticket_" + ticketId + "' title='" + subject + "'>" + (subject == '' ? '#' + ticketId : subject) + "</a>" +
                    "<div class='ticket-close' id='close" + ticketId + "' data-id='a_viewticket_" + ticketId + "' title='Close' onclick='tabticketclose(" + ticketId + ")'>x</div></li>");
                $('#tabpanel-viewticket').append(data);
                initJQueryViewTicket(ticketId);
            }
            App.unblockUI($('#dashboard'));
        },
        error: function () {
            App.unblockUI($('#dashboard'));
        }
    });
}


function refreshticket(ticketId, isblocked) {
    if (!isblocked) App.blockUI($('#viewticket_' + ticketId));
    $.ajax({
        url: '/Ticket/TicketDetails',
        data: { ticketId: ticketId },
        success: function (data) {
            $('#viewticket_' + ticketId).replaceWith(data);
            initJQueryViewTicket(ticketId);
            initformlistticket();
            App.unblockUI($('#viewticket_' + ticketId));
        },
        error: function () {
            App.unblockUI($('#viewticket_' + ticketId));
        }
    });
}
function refreshlistcurrent() {
    App.blockUI($('#listcurrentticket'));
    $.ajax({
        url: '/Ticket/CurrentTicket',
        success: function (data) {
            $('#listcurrentticket').html(data);
            $(".ticket-filter-curent li").click(function () {
                $(".ticket-filter-curent li").removeClass("active");
                $(this).addClass("active");
            });
            $(".btn-refresh-board i").removeClass("icon-spin");
            App.unblockUI($('#listcurrentticket'));
        },
        error: function () {
            App.unblockUI($('#listcurrentticket'));
        }
    });
}
function initJQueryViewTicket(ticketId) {
    $('#datetimepicker2_' + ticketId).datetimepicker({
        language: 'en',
        pick12HourFormat: true
    });
    //$('#EmailCc_' + ticketId).tagsInput({ defaultText: "Add a email", width: "95%" });
    //$('#EmailBcc_' + ticketId).tagsInput({ defaultText: "Add a email", width: "95%" });
    initfrViewTicketSubmit(ticketId);
    initFrUploadFile(ticketId);
    var h = $(window).height() - $("#tabpanel-viewticket").offset().top - 160;
    $('#viewticket_' + ticketId + ' .TicketCommentDetail').slimScroll({
        height: h,
        alwaysVisible: true
    });
    //var h2 = $(window).height() - $("#tabpanel-viewticket").offset().top - 222;
    //$(".ticket-left").css("height", h2 + "px");
}
function AddRelationTaskID(ticketId, taskId) {
    if (taskId == '') {
        alert("Please enter TaskId");
        return;
    }
    App.blockUI($('#viewticket_' + ticketId));
    $.ajax({
        url: "/ticket/AddRelationTaskID",
        data: { ticketId: ticketId, taskId: taskId },
        success: function (data) {
            if (data != "") {
                alert(data);
            } else {
                $('#ListRelationTaskID_' + ticketId).append("<a href='#'  onclick=\"PopupCenter('/orderview/viewtask/'" + taskId + ", 600, 540);\" style='cursor: pointer' title='View Order'>" + taskId + " ,</a>");
                $("#TaskID_" + ticketId).val('');
            }
            App.unblockUI($('#viewticket_' + ticketId));
        }, error: function () {
            alert('error!');
            App.unblockUI($('#viewticket_' + ticketId));
        }
    });
}
function AddRelationOrderRef(ticketId, orderRef) {
    if (orderRef == '') {
        alert("Please enter OrderRef");
        return;
    }
    App.blockUI($('#viewticket_' + ticketId));
    $.ajax({
        url: "/ticket/AddRelationOrderRef",
        data: { ticketId: ticketId, OrderRef: orderRef },
        success: function (data) {
            if (data != "") {
                alert(data);
            } else {
                $('#ListRelationOrerdRef_' + ticketId).append("<a href=\"/orderview/orderdetail?OrderRef=" + orderRef + "\" target=\"blank\" style=\"cursor: pointer\" title=\"View Order\">" + orderRef + " ,</a>");
                $("#OrderRef_" + ticketId).val('');
            }
            App.unblockUI($('#viewticket_' + ticketId));
        }, error: function () {
            alert('error!');
            App.unblockUI($('#viewticket_' + ticketId));
        }
    });
}
function AddRelationDisputeId(ticketId, disputeId) {
    if (disputeId == '') {
        alert("Please enter disputeId");
        return;
    }
    App.blockUI($('#viewticket_' + ticketId));
    $.ajax({
        url: "/ticket/AddRelationDisputeId",
        data: { ticketId: ticketId, disputeId: disputeId },
        success: function (data) {
            if (data != "") {
                alert(data);
            } else {
                $('#AddRelationDisputeId_' + ticketId).append("<a>" + disputeId + " ,</a>");
                $("#DisputeID_" + ticketId).val('');
            }
            App.unblockUI($('#viewticket_' + ticketId));
        }, error: function () {
            alert('error!');
            App.unblockUI($('#viewticket_' + ticketId));
        }
    });
}

function initfrViewTicketSubmit(ticketId) {
    $('#frViewTicket_' + ticketId).submit(function () {
        if (ticketId == 0) {
            App.blockUI($('#newticket'));
        }
        App.blockUI($('#viewticket_' + ticketId));
        var check = $("#hfaddtask_" + ticketId).val();
        $("#hfaddtask_" + ticketId).val('false');
        $.ajax({
            url: "/ticket/SubmitTicket",
            data: $(this).serialize(),
            method: "POST",
            success: function (data) {
                if (data != "") {
                    if (ticketId == 0) {
                        App.unblockUI($('#newticket'));
                        alert("New ticket has been added");
                        viewticket(data, "");
                        //$('#btnResetFormAddTicket').click();
                        $.ajax({
                            url: "/ticket/newticket",
                            success: function (response) {
                                $("#newticket").html(response);
                                initFrUploadFile(ticketId);
                            }
                        });
                    } else
                        alert(data);
                    App.unblockUI($('#viewticket_' + ticketId));
                } else {
                    alert("Ticket has been updated");
                    refreshticket(ticketId, true);
                    if (check == 'true') {
                        $.ajax({
                            url: "/ticket/addtaskfromticket",
                            data: { ticketId: ticketId },
                            success: function (res) {
                                $('#ModalAddTaskFromTicket').html(res);
                                App.unblockUI($('#viewticket_' + ticketId));
                                initfrAddTaskSubmit(ticketId);
                                $('#ModalAddTaskFromTicket').modal();
                            },
                            error: function () {
                                App.unblockUI($('#viewticket_' + ticketId));
                            }
                        });
                    }
                }
                $("#hfcommentOrSubmit_" + ticketId).val("");
            }, error: function () {
                App.unblockUI($('#viewticket_' + ticketId));
            }
        });
        return false;
    });
}
function SetIsPublicReply(isPublicReply, ticketId) {
    $("#IsPublicReply_" + ticketId).val(isPublicReply);
    if (isPublicReply == 1) {
        $("#btnSetInternalNote_" + ticketId).removeClass("btn-warning");
        $("#btnSetPublicReply_" + ticketId).addClass("btn-primary");
        $("#noteIsReply_" + ticketId).html("| your comment is sent to the ticket requester");
        $("#NewComment_" + ticketId).removeClass("ticket-comment-warning");
    } else {
        $("#btnSetInternalNote_" + ticketId).addClass("btn-warning");
        $("#btnSetPublicReply_" + ticketId).removeClass("btn-primary");
        $("#noteIsReply_" + ticketId).html("| your comment is visible to agents only");
        $("#NewComment_" + ticketId).addClass("ticket-comment-warning");
    }
}
function initFrUploadFile(ticketId) {
    $("#mulitplefileuploader_" + ticketId).uploadFile({
        url: "/ticket/UploadTicketAttachment",
        method: "POST",
        fileName: "fileUpload",
        multiple: true,
        onSuccess: function (files, data, xhr) {
            if (data != "") {
                $('#LstAttachment_' + ticketId).append("<li><input type=\"hidden\" name=\"FileAttachments\" value=\"" + data + "\"/><i class='icon-file'style='color: #777;'></i><a>" + data.split("\\").pop() + "</a><a href='#' class='ticket-remove-attachment' title='Removing attachment'onclick='$(this).parent().remove()'>x</a></li>");
            }
            $("#status_" + ticketId).html("<font color='green'>Upload is success</font>");

        },
        onError: function (files, status, errMsg) {
            $("#status_" + ticketId).html("<font color='red'>Upload is Failed</font>");
        }
    });

    $("#frUploadfile_" + ticketId).submit(function () {
        App.blockUI($('#viewticket_' + ticketId));
        //grab all form data  
        var formData = new FormData($("#frUploadfile_" + ticketId)[0]);
        $.ajax({
            url: '/ticket/UploadTicketAttachment',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                if (data != "") {
                    $('#LstAttachment_' + ticketId).append("<li><input type=\"hidden\" name=\"FileAttachments\" value=\"" + data + "\"/><i class='icon-file'style='color: #777;'></i><a>" + data.split("\\").pop() + "</a><a href='#' class='ticket-remove-attachment' title='Removing attachment'onclick='$(this).parent().remove()'>x</a></li>");
                }
                App.unblockUI($('#viewticket_' + ticketId));
            },
            error: function (error) {
                App.unblockUI($('#viewticket_' + ticketId));
            }
        });
        return false;
    });
}

function SetGroupOrderRefStatus(exist) {
    if (exist) {
        $("#TaskOrderRef").css("border-color", "green");
        $("#TaskOrderRef").attr('title', 'OrderRef exist');
        $("#TaskOrderRef").tooltip('destroy');
        $("#TaskOrderRef").tooltip();
    } else {
        $("#TaskOrderRef").css("border-color", "red");
        $("#TaskOrderRef").attr('title', 'OrderRef incorrect');
        $("#TaskOrderRef").tooltip('destroy');
        $("#TaskOrderRef").tooltip('show');
    }
}
function CheckOrderRefExist(orderRef) {
    $.ajax({
        type: "POST",
        url: '/OrderView/CheckOrderRef',
        data: { orderref: orderRef },
        dataType: "text",
        success: function (data) {
            if (data == 'True') {
                SetGroupOrderRefStatus(true);
                return true;
            } else {
                SetGroupOrderRefStatus(false);
                return false;
            }
        }
    });
}
function gettitles(taskTypeId) {
    $.ajax({
        url: "/task/gettitles",
        data: { taskTypeId: taskTypeId },
        success: function (data) {
            $("#TaskTitleID").html('');
            $.each(data, function (id, option) {
                $("#TaskTitleID").append($('<option></option>').val(option.id).html(option.name));
            });
        }
    }
    );
}

function initfrAddTaskSubmit(ticketId) {
    $('#frAddTask').submit(function () {
        App.blockUI($("#frAddTask"));
        var err = false;
        err = checkaddtaskrequirederr($("#TaskTypeID")) || err;
        err = checkaddtaskrequirederr($("#TaskTitleID")) || err;
        err = checkaddtaskrequirederr($("#ReasonID")) || err;
        err = checkaddtaskrequirederr($("#PriorityID")) || err;
        err = checkaddtaskrequirederr($("#AssignedToUser")) || err;
        $("#TaskDescription").removeClass("addtask-required-warring");
        if ($("#TaskDescription").val() == "") {
            $("#TaskDescription").addClass("addtask-required-warring");
            err = true;
        }
        if (err) {
            App.unblockUI($("#frAddTask"));
            alert("Some field has not been filled. Check and fill it, please!");
        } else {
            var submitData = $(this).serialize();
            $.ajax({
                type: "POST",
                url: '/OrderView/CheckOrderRef',
                data: { orderref: $("#TaskOrderRef").val() },
                dataType: "text",
                success: function (data) {
                    if (data == 'True' || $("#TaskOrderRef").val() == '') {
                        $.ajax({
                            type: 'POST',
                            url: '/Ticket/AddTaskFromTicket',
                            cache: false,
                            data: submitData,
                            success: function () {
                                App.unblockUI($(".modal"));
                                $('#ModalAddTaskFromTicket').modal('hide');
                                refreshticket(ticketId);
                                alert("New Task has been linked to this ticket");
                            }
                        });
                    } else {
                        App.unblockUI($("#frAddTask"));
                        SetGroupOrderRefStatus(false);
                        $("#TaskOrderRef").focus();
                        $("#TaskOrderRef").tooltip('destroy');
                        $("#TaskOrderRef").tooltip('show');
                    }
                }
            });
        }
        return false;
    });
}
function checkaddtaskrequirederr(selector) {
    selector.removeClass("addtask-required-warring");
    var err = false;
    if (selector.val() == 0) {
        selector.addClass("addtask-required-warring");
        err = true;
    }
    return err;
}

function ticketpaging(page, departmentid, filterStatus) {
    App.blockUI($('#divListTicket'));
    $.ajax({
        url: "/ticket/ListTicket",
        data: { filterStatus: filterStatus, departmentid: departmentid, p: page },
        success: function (data) {
            $('#divListTicket').html(data);
            $('.showSummary').tooltip111();
            var height = $(".ticket-filter").height();
            $(".listticketresult").slimScroll({
                height: height - 60
            });
            initformlistticket();
            App.unblockUI($('#divListTicket'));
            autorefreshticketpaging(page, departmentid, filterStatus);
        }
    });
}

function autorefreshticketpaging(page, departmentid, filterStatus) {
    clearInterval(refreshlistticket);
    refreshlistticket = setInterval(function () {
        $.ajax({
            url: "/ticket/ListTicket",
            data: { filterStatus: filterStatus, departmentid: departmentid, p: page },
            success: function (data) {
                $('#divListTicket').html(data);
                $('.showSummary').tooltip111();
                var height = $(".ticket-filter").height();
                $(".listticketresult").slimScroll({
                    height: height - 60
                });
                initformlistticket();
            }
        });
    }, 30000);
}


function FilterTicket(departmentid, filterStatus, $divResult) {
    if (filterStatus > 0 && filterStatus <= 7) {
        $("#hf-statusid").val(filterStatus);
    }
    $("#hf-departmentid").val(departmentid);
    App.blockUI($divResult);
    $.ajax({
        url: "/ticket/ListTicket",
        data: { filterStatus: filterStatus, departmentid: departmentid },
        success: function (data) {
            $divResult.html(data);
            $("#listcurrentticket table input[type='checkbox']").hide();
            $('.showSummary').tooltip111();
            var height = $(".ticket-filter").height();
            $(".listticketresult").slimScroll({
                height: height - 60
            });
            initformlistticket();
            App.unblockUI($divResult);
            autorefreshlistticket(departmentid, filterStatus, $divResult);
        }
    });
}

function autorefreshlistticket(departmentid, filterStatus, $divResult) {
    clearInterval(refreshlistticket);
    refreshlistticket = setInterval(function () {
        $.ajax({
            url: "/ticket/ListTicket",
            data: { filterStatus: filterStatus, departmentid: departmentid },
            success: function (data) {
                $divResult.html(data);
                $("#listcurrentticket table input[type='checkbox']").hide();
                $('.showSummary').tooltip111();
                var height = $(".ticket-filter").height();
                $(".listticketresult").slimScroll({
                    height: height - 60
                });
                initformlistticket();
            }
        });
    }, 30000);
}

function sortticket(cell, statusid, departmentid, $divResult) {
    var sort = cell.attr('data-sort');
    App.blockUI($divResult);
    $.ajax({
        url: "/ticket/listticket",
        data: { col: cell.html(), sort: sort, filterStatus: statusid, departmentid: departmentid },
        success: function (data) {
            $divResult.html(data);
            $('.showSummary').tooltip111();
            var height = $(".ticket-filter").height();
            $(".listticketresult").slimScroll({
                height: height - 60
            });
            initformlistticket();
            App.unblockUI($divResult);
            autorefreshsortticket(cell, statusid, departmentid, $divResult)
        }
    });
}

function autorefreshsortticket(cell, statusid, departmentid, $divResult) {
    var sort = cell.attr('data-sort');
    clearInterval(refreshlistticket);
    refreshlistticket = setInterval(function () {
        $.ajax({
            url: "/ticket/listticket",
            data: { col: cell.html(), sort: sort, filterStatus: statusid, departmentid: departmentid },
            success: function (data) {
                $divResult.html(data);
                $('.showSummary').tooltip111();
                var height = $(".ticket-filter").height();
                $(".listticketresult").slimScroll({
                    height: height - 60
                });
                initformlistticket();
                App.unblockUI($divResult);
            }
        });
    }, 30000);
}

function ViewTicketHistory(ticketId) {
    App.blockUI($('#viewticket_' + ticketId));
    $.ajax({
        method: "GET",
        url: "/Ticket/ViewTicketHistory",
        data: { ticketId: ticketId },
        success: function (data) {
            $("#ModalViewTicketHistory").html(data);
            $("#ModalViewTicketHistory").modal();
            App.unblockUI($('#viewticket_' + ticketId));
        },
        error: function () {
            $("#ModalViewTicketHistory").html("Load failed");
            App.unblockUI($('#viewticket_' + ticketId));
        }
    });
}
function CloseTicket(ticketId, filterStatusId) {
    if (confirm('Are you sure to close this ticket ?')) {
        $.ajax({
            url: "/ticket/SubmitTicket",
            data: $(this).serialize(),
            success: function (data) {
                alert("This ticket has been closed");
                //viewticket(filterStatusId);
            },
            error: function () {
            }
        });
    }
}

function LoadJqueryNewTicket() {
    $("#newticket .tagsinput").remove();
    $('#newticket #EmailCc_0').tagsInput({ defaultText: "Add a email", width: "95%" });
    $('#newticket #EmailBcc_0').tagsInput({ defaultText: "Add a email", width: "95%" });
}
function AddBlackList(email) {
    if (confirm('Are you sure to add email ' + email + ' to black list ?')) {
        $.ajax({
            url: "/ticket/AddBlackList",
            data: { email: email },
            success: function (data) {
                alert("This email has been added to black list");
            },
            error: function () {
            }
        });
    }
}
function RemoveBlackList(id, email) {
    if (confirm('Are you sure to remove ' + email + ' from black list ?')) {
        $.ajax({
            url: "/ticket/RemoveBlackList",
            data: { id: id },
            success: function (data) {
                ViewBlackList();
                alert(email + " has been removed from black list");
            },
            error: function () {
            }
        });
    }
}
function ViewBlackList() {
    App.blockUI($('#divListBlackList'));
    $.ajax({
        method: "GET",
        url: "/Ticket/ViewBlackList",
        success: function (data) {
            $('#divListBlackList').html(data);
            $('#divSignature').hide();
            $('#divListBlackList').show();
            App.unblockUI($('#divListBlackList'));
        },
        error: function () {
            App.unblockUI($('#divListBlackList'));
        }
    });
}

function ViewUserSignature() {
    App.blockUI($('#Settings'));
    if ($("#divSignature").html() == '') {
        $.ajax({
            method: "GET",
            url: "/Ticket/UserSignature",
            success: function (data) {
                $('#divSignature').show();
                $('#divSignature').html(data);
                $('#divListBlackList').hide();
                //InitSaveUserSignature();
                App.unblockUI($('#Settings'));
            },
            error: function () {
                App.unblockUI($('#Settings'));
            }
        });
    } else {
        $('#divSignature').show();
        $('#divListBlackList').hide();
        App.unblockUI($('#Settings'));
    }
}
function InitSaveUserSignature() {
    $('#frSaveSignature').submit(function () {
        var x = $(this).serialize();
        App.blockUI($('#divListBlackList'));
        $.ajax({
            method: "POST",
            url: "/Ticket/SaveSignature",
            data: $(this).serialize(),
            success: function (data) {
                if (data == '') {
                    alert("Save success");
                }
                App.unblockUI($('#divListBlackList'));
            },
            error: function () {
                App.unblockUI($('#divListBlackList'));
            }
        });
        return false;
    });
}
function RetreiveTicket(ticketId) {
    App.blockUI($('#viewticket_' + ticketId));
    $.ajax({
        url: "/ticket/RetreiveTicket",
        data: { ticketId: ticketId },
        method: "POST",
        success: function (data) {
            if (data != "") {
                alert(data);
                App.unblockUI($('#viewticket_' + ticketId));
            } else {
                alert("Ticket has been updated");
                refreshticket(ticketId, true);
            }
        }, error: function () {
            App.unblockUI($('#viewticket_' + ticketId));
        }
    });
}
function linkmailtootherticket(emailId, ticketId) {
    App.blockUI($('#viewticket_' + ticketId));
    $.ajax({
        method: "GET",
        url: "/Ticket/LinkMailToOtherTicket",
        data: { emailId: emailId },
        success: function (data) {
            $("#ModalLinkMailToOtherTicket").html(data);
            $("#ModalLinkMailToOtherTicket").modal();
            App.unblockUI($('#viewticket_' + ticketId));
        },
        error: function () {
            $("#ModalLinkMailToOtherTicket").html("Load failed");
            App.unblockUI($('#viewticket_' + ticketId));
        }
    });
}
function linkemailtoticket(ticketId, emailId) {
    var isClose = false;
    if (confirm("Do you want to close parent ticket!")) {
        isClose = true;
    }
    $.ajax({
        method: "POST",
        url: "/Ticket/LinkMailToOtherTicket",
        data: { emailId: emailId, ticketId: ticketId, isCloseTicket: isClose },
        success: function (data) {
            alert("This email has been linked to ticket #" + ticketId);
            $("#ModalLinkMailToOtherTicket").modal("hide");

        },
        error: function () {
            alert("Error!");
        }
    });
}

function ShowQuickReply(ticketId, to) {
    $("#ModalQuickReply").html("<div class=\"ajax-loading\"></div>");
    $("#ModalQuickReply").modal("show");
    $.ajax({
        url: "/ticket/getcontentquickreply",
        data: { ticketid: ticketId, to: to },
        success: function (data) {
            $("#ModalQuickReply").html(data);
        }
    });
}

function commentnotsubmitticket(ticketid) {
    $("#hfcommentOrSubmit_" + ticketid).val("comment");
    $('#frViewTicket_' + ticketid).submit();
}

function initformlistticket() {
    $(".checkallticket").click(function () {
        if ($(this).is(":checked")) {
            $('#divListTicket table input[type="checkbox"]').prop("checked", true);
            $(".btn-deletetickets").show();
            $(".assign-div").show();
        } else {
            $('#divListTicket table input[type="checkbox"]').prop("checked", false);
            $(".btn-deletetickets").hide();
            $(".assign-div").hide();
        }
    });

    $('#divListTicket tbody input[type="checkbox"]').click(function () {
        var show = false;
        $('#divListTicket tbody input[type="checkbox"]').each(function () {
            if ($(this).is(":checked")) {
                show = true;
            }
        });
        if (show) {
            $(".btn-deletetickets").show();
            $(".assign-div").show();
        } else {
            $(".btn-deletetickets").hide();
            $(".assign-div").hide();
        }
    });
    $('#divListTicket #fr-listticket').submit(function () {
        var serializedForm = $(this).serialize();
        App.blockUI($('#divListTicket'));
        if (checkD == 0) {
            $.ajax({
                type: 'POST',
                url: '/ticket/deletetickets',
                data: serializedForm,
                success: function (data) {
                    $(".btn-deletetickets").hide();
                    $(".assign-div").hide();
                    refreshTree();
                    $('#divListTicket').html(data);
                    $('.showSummary').tooltip111();
                    //$divResult.slimScroll();
                    var height = $(".ticket-filter").height();
                    $(".listticketresult").slimScroll({
                        height: height - 60,
                        alwaysVisible: true
                    });
                    initformlistticket();
                    App.unblockUI($('#divListTicket'));
                },
                error: function () {
                    alert('Error!');
                    App.unblockUI($('#divListTicket'));
                }
            });
            checkD = 2;
        } else if (checkD == 1) {
            var value = $("#AssignToUserId").val();
            if (value > 0) {
                $.ajax({
                    type: 'POST',
                    url: '/ticket/AssignTickets',
                    data: serializedForm + "&AssignToUserId=" + value,
                    success: function (data) {
                        $(".btn-deletetickets").hide();
                        $(".assign-div").hide();
                        refreshTree();
                        $('#divListTicket').html(data);
                        $('.showSummary').tooltip111();
                        //$divResult.slimScroll();
                        var height = $(".ticket-filter").height();
                        $(".listticketresult").slimScroll({
                            height: height - 60,
                            alwaysVisible: true
                        });
                        initformlistticket();
                        App.unblockUI($('#divListTicket'));
                    },
                    error: function () {
                        alert('Error!');
                        App.unblockUI($('#divListTicket'));
                    }
                });
            } else {
                App.unblockUI($('#divListTicket'));
                alert("Please select user");
            }
            checkD = 2;
        }
        return false;
    });
}

//AUTO REFRESH

function refreshcomment(button, ticketid) {
    button.find("i").addClass("icon-spin");
    setTimeout(function () {
        button.find("i").removeClass("icon-spin");
    }, 2e3);
    App.blockUI($('#commentticket_' + ticketid), false);
    $.ajax({
        url: '/ticket/refreshcomment?ticketid=' + ticketid,
        success: function (data) {
            $("#commentticket_" + ticketid).html(data);
        }
    });
}






(function ($) {
    jQuery.fn.tooltip111 = function (options) {
        var defaults = {
            offsetX: 15,  //X Offset value
            offsetY: 20,  //Y Offset value
            fadeIn: '200', //Tooltip fadeIn speed, can use, slow, fast, number
            fadeOut: '100', //Tooltip fadeOut speed, can use, slow, fast, number
            dataAttr: 'data', //Used when we create seprate div to hold your tooltip data, so plugin search div tage by using id 'data' and current href id on whome the mouse pointer is so if your href id is '_tooltip_1' then the div which hold that tooltips content should have id 'data_tooltip_1', if you change dataAttr from default then you need to build div tag with id 'current dataAttr _tooltip_1' without space
            bordercolor: '#ccc', // tooltip border color
            bgcolor: '#FFF', //Tooltip background color
            fontcolor: '#000', //Tooltip Font color
            fontsize: '12px', // Tooltip font size
            folderurl: 'NULL', // Folder url, where the tooltip's content file is placed, needed with forward slash in the last (/), or can be use as http://www.youwebsitename.com/foldername/ also.
            filetype: 'txt', // tooltip's content files type, can be use html, txt
            height: 'auto', // Tooltip's width
            width: '500', //Tooltip's Height
            cursor: 'cursor' // Mouse cursor
        };
        var options = $.extend(defaults, options);
        //Runtime div building to hold tooltip data, and make it hidden
        var $tooltip = $('<div id="divToolTip"></div>');
        return this.each(function () {
            $('body').append($tooltip);
            $tooltip.hide();
            //Runtime variable definations
            var element = this;
            var id = $(element).attr('data-id');
            var filename = options.folderurl + id + '.' + options.filetype;
            var dialog_id = '#divToolTip';
            //Tooltips main function
            $(this).hover(function (e) {
                if (!$('#' + id).hasClass('IsLoaded')) {
                    $('#' + id + " .protip-content").html("<div class='ajax-loading'></div>");
                    $(dialog_id).html($('#' + id).html());
                    $.ajax({
                        method: "GET",
                        url: "/Ticket/TicketEmailDetail",
                        data: { emailid: $('#' + id).data("emailid") },
                        success: function (data) {
                            $('#' + id + " .protip-content").html(data);
                            $('#' + id).addClass('IsLoaded');
                            $(dialog_id).html($('#' + id).html());
                        }
                    });
                } else {
                    $(dialog_id).html($('#' + id).html());
                }

                //assign css value to div
                $(element).css({ 'cursor': options.cursor });
                if ($(document).width() / 2 < e.pageX) {
                    $(dialog_id).css({
                        'position': 'absolute',
                        'border': '1px solid ' + options.bordercolor,
                        'background-color': options.bgcolor,
                        'padding': '0',
                        'top': e.pageY + options.offsetY,
                        'left': e.pageX - $(dialog_id).width() + options.offsetX,
                        'color': options.fontcolor,
                        'font-size': options.fontsize,
                        'width': options.width
                    });
                } else {
                    $(dialog_id).css({
                        'position': 'absolute',
                        'border': '1px solid ' + options.bordercolor,
                        'background-color': options.bgcolor,
                        'padding': '0',
                        'top': e.pageY + options.offsetY,
                        'left': e.pageX + options.offsetX,
                        'color': options.fontcolor,
                        'font-size': options.fontsize,
                        'cursor': options.cursor,
                        'width': options.width
                    });
                    //alert(size);
                }
                //enable div block
                $(dialog_id).stop(true, true).fadeIn(options.fadeIn);


            }, function () {
                // when mouse out remove all data from div and make it hidden
                $(dialog_id).stop(true, true).fadeOut(options.fadeOut);
            }).mousemove(function (e) {
                // to make tooltip moveable with mouse	
                if ($(document).width() / 2 < e.pageX) {
                    $(dialog_id).css({
                        'top': e.pageY + options.offsetY,
                        'left': e.pageX - $(dialog_id).width(),
                        'height': options.height,
                        'width': options.width
                    });
                    //$(dialog_id).html(e.pageX - $(dialog_id).width());
                } else {
                    $(dialog_id).css({
                        'top': e.pageY + options.offsetY,
                        'left': e.pageX + options.offsetX,
                        'height': options.height,
                        'width': options.width
                    });
                }
            });
        });
    };
})(jQuery);

//FINISH, simple isnt it ??
//if you like it or have any suggestions / comments , or you have some idea to make it better, 
//or you need some more fetures in it PLS PLS PLS let me know that at
//i.rizvi@hotmail.com
//Thank you for using my plugin

$(document).ready(function () {
    $('.showSummary').tooltip111();
});
